<template>
  <div class="body">
    <div style="display: flex;">
      <!-- 714晚上极限拯救队友代码 -->
      <!-- {{ puncherArr }} -->
      <!-- {{ treeSelect }} -->


      <div class="btn-left checked-area" style="width: 50%; border-right: 1px solid #F2F4FA;padding: 24px;">
        <div v-if="puncherMemberModal">
          <div class="btn-tit">部门</div>
          <div class="tag-btn" style="display: flex;margin: 10px 0 20px 0;flex-wrap: wrap;">
            <div class="item" v-for="(item,index) in getDepartmentList" :key="item.id">
              <span class="label">{{ item.nickName }} ( {{ item.personCount }} )</span>
            </div>
            <div v-if="!getDepartmentList.length" style="color:#999999">暂无部门</div>
          </div>
          <div class="btn-tit">人员</div>
          <div class="tag-btn" style="display: flex;margin-top: 10px;flex-wrap: wrap;">
            <div class="item" v-for="item in selectedTeacherList" :key="item.userId">
              <span class="label">{{ item.userName }}</span>
              <a-icon class="icon" type="close" @click="delCheckedEvt(item.userId, 'T', item.departmentId)" />
            </div>
            <div v-if="!selectedTeacherList.length" style="color:#999999">暂无部门</div>
          </div>
        </div>
        <div v-else>
          <div class="btn-tit">人员</div>
          <div class="item" v-for="item in selectedTeacher2List" :key="item.userId">
            <span class="label">{{ item.userName }}</span>
            <a-icon class="icon" type="close" @click="delCheckedEvt2(item.userId, 'T', item.departmentId)" />
          </div>
          <div v-if="!selectedTeacher2List.length" style="color:#999999">暂无部门</div>
        </div>
      </div>
      <div style="padding: 24px;">
        <div v-if="puncherMemberModal">
          <a-tabs default-active-key="2">
            <a-tab-pane key="1">
              <span slot="tab">部门</span>
              <a-tree checkable v-model="treeSelect" :tree-data="departemntList" @check="departmentSelect"
                :replaceFields="{
                  children:'child',
                  title:'name',
                  key:'id'
                }" />
            </a-tab-pane>
            <a-tab-pane key="2">
              <span slot="tab">人员</span>
              <a-tree v-model="checkedTeacherList" :tree-data="teacherList" checkable @check="onTeacherChange"></a-tree>
            </a-tab-pane>
          </a-tabs>
        </div>
        <div v-else>
          <a-tree v-model="checkedTeacher2List" :tree-data="teacherList" checkable @check="onTeacher2Change"></a-tree>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import {
    tree,
    allTeacherAndTree,
    allTeacherAndTreeP,
    calendarInfo,
    teacherList,
  } from '@/api/tree'
  export default {
    data() {
      return {
        treeList: [],
        treeSelect: [],
        allSelect: [],

        departemntList: [],

        teacherList: [],
        checkedTeacherList: [],
        selectedTeacherList: [],

        teacher2List: [],
        checkedTeacher2List: [],
        selectedTeacher2List: [],

        PunchersTxt: '',
        OwnerTxt: '',

        groupId: null,
        punchGroupInfo: {
          deptParams: [],
          groupName: undefined,
          id: undefined, // 考勤组id
          leaderParams: [],
          memberParams: []
        },
        allTeacherList: [],
        // 选中项目
        checkedPuncher: [],
        checkedOwner: [],
        checkedDepartment: [],

        selectDepartment: [],

        // 打卡者 ｜ 负责人
        puncherArr: [],
        ownerArr: [],
        departmentArr: [],

        puncherMemberModal: false,
        ownerMemberModal: false,
      }
    },
    computed: {
      getDepartmentList() {
        const readNodes = (nodes = [], arr = []) => {
          for (let item of nodes) {
            // if (this.treeSelect.includes(item.id) && !item.child?.length) {
            if (this.treeSelect.includes(item.id)) {
              arr.push(item)
            }
            if (item.child?.length) readNodes(item.child, arr)
          }
          return arr
        }
        return readNodes(this.departemntList)
      },
      getOwners() {
        let tempArr = []
        this.checkedOwner.forEach(item => {
          tempArr.push(JSON.parse(item).userName)
        })
        return tempArr.join(',')
      }
    },
    watch: {

    },
    created() {
      this.getMemberTreeData()

      this.showMemberModal(1)

    },
    methods: {

      departmentSelect(e) {
        console.log("e: ", e);
        let departmentArr = []
        this.treeList.forEach(item => {
          e.forEach(item1 => {
            if (item1 == item.userId) treeList.push(item)
          })
        })
        this.departmentArr = departmentArr
        console.log("this.departmentArr: ", this.departmentArr)
      },

      punchMemberSelect(e) {
        if (this.puncherMemberModal) {
          let puncherArr = []
          this.allTeacherList.forEach(item => {
            e.forEach(item1 => {
              if (item1 == item.userId) puncherArr.push(item)
            })
          })
          this.puncherArr = puncherArr
          console.log("this.puncherArr: ", this.puncherArr)
        } else {
          let ownerArr = []
          this.allTeacherList.forEach(item => {
            e.forEach(item1 => {
              if (item1 == item.userId) ownerArr.push(item)
            })
          })
          this.ownerArr = ownerArr
          console.log("this.ownerArr: ", this.ownerArr)
        }
      },

      // step--1
      showMemberModal(type) {
        let tempArr = this.allTeacherList
        this.allTeacherList = []
        this.allTeacherList = tempArr
        if (type == 1) {
          this.puncherMemberModal = true
          this.ownerMemberModal = false
        }
        if (type == 2) {
          this.puncherMemberModal = false
          this.ownerMemberModal = true
        }
      },

      // 获取树数据
      getMemberTreeData() {
        tree({
          parentId: 0
        }).then(response => {
          this.departemntList = response.data.list
          allTeacherAndTreeP().then(response => {
            this.allTeacherList = response.data.departmentTree
            console.log("this.allTeacherListthis.allTeacherList: ", this.allTeacherList);
          })
        })
      },


      getPunchersTxt() {
        console.log("this.puncherMemberModal: ", this.puncherMemberModal);

        if (this.puncherMemberModal) {
          // selectedTeacherList }}{{ getDepartmentList
          console.log("this.部门: ", this.getDepartmentList);
          console.log("this.人员: ", this.selectedTeacherList);
          let str = ''
          if (this.getDepartmentList.length) {
            this.getDepartmentList.forEach(item => {
              str = str + item.nickName + '(' + item.personCount + ')'
            })
          }
          if (this.selectedTeacherList.length) {
            this.selectedTeacherList.forEach(item => {
              str = str + ' ' + item.userName
            })
          }
          console.log("str: ", str);
          this.PunchersTxt = str
          this.puncherMemberModal = false
          this.ownerMemberModal = false
        } else {
          let str = ''
          if (this.selectedTeacher2List.length) {
            this.selectedTeacher2List.forEach(item => {
              str = str + ' ' + item.userName
            })
          }
          console.log("str: ", str);
          this.OwnerTxt = str
          this.puncherMemberModal = false
          this.ownerMemberModal = false
        }
      },

      //查找所有父节点  返回id集合
      getParentIds(list, id) {
        for (let i in list) {
          if (list[i].id === id || list[i].userId === id) {
            return [];
          }
          if (list[i].children) {
            let node = this.getParentIds(list[i].children, id);
            if (node) {
              return node.concat(list[i].id);
            }
          }
        }
      },


      async getModinMemberList() {
        let r = (await allTeacherAndTree()).data
        this.handleTreeData(r.departmentTree)
        this.teacherList = r.departmentTree
        // this.handleTreeData(r.data.departmentTree);
        // this.teacherList = r.data.departmentTree;
        // if (r.message === "success") {
        //   this.handleTreeData(r.data.departmentTree);
        //   this.teacherList = r.data.departmentTree;
        // } else {
        //   this.$message.warning(r.message);
        // }
      },
      handleTreeData(data) {
        for (let i = 0; i < data.length; i++) {
          const item = data[i];
          const {
            id,
            userId,
            name,
            child,
            personList
          } = item;
          item.title = name;
          item.key = id || userId;
          item.children = child && child.length ? child : personList;
          if ((child && child.length) || (personList && personList.length)) {
            this.handleTreeData(child && child.length ? child : personList);
          }
        }
      },


      onTeacherChange(checkedValues, checkedNodes) {
        this.checkedTeacherList = checkedValues;
        let arr = [];
        checkedNodes.checkedNodesPositions.forEach((item) => {
          const {
            name,
            userId,
            userIndex,
            departmentId,
            child,
            personList
          } =
          item.node.data.props;
          if (!child || !personList) {
            arr.push({
              userName: name,
              userId,
              userIndex,
              departmentId,
              userType: "T",
            });
          }
        });
        this.selectedTeacherList = arr;
      },

      delCheckedEvt(userId, type) {
        if (type === "T") {
          const result = this.getParentIds(this.teacherList, userId)
          console.log("mmmm", result)
          this.selectedTeacherList = this.selectedTeacherList.filter(
            (v) => v.userId !== userId
          );
          this.checkedTeacherList = this.checkedTeacherList.filter(
            (v) => v !== userId && !result.includes(v)
          );
        } else if (type === "S") {
          const result = this.getParentIds(this.studentList, userId)
          console.log("mmmm", result)
          this.selectedStudentList = this.selectedStudentList.filter(
            (v) => v.userId !== userId
          );
          this.checkedStudentList = this.checkedStudentList.filter(
            (v) => v !== userId && !result.includes(v)
          );

        } else {
          this.selectedRoleList = this.selectedRoleList.filter(
            (v) => v.roleCode !== userId
          );
          this.checkedRoleList = this.checkedRoleList.filter((v) => v !== userId);
        }
      },
      onTeacher2Change(checkedValues, checkedNodes) {
        this.checkedTeacher2List = checkedValues;
        let arr = [];
        checkedNodes.checkedNodesPositions.forEach((item) => {
          const {
            name,
            userId,
            userIndex,
            departmentId,
            child,
            personList
          } =
          item.node.data.props;
          if (!child || !personList) {
            arr.push({
              userName: name,
              userId,
              userIndex,
              departmentId,
              userType: "T",
            });
          }
        });
        this.selectedTeacher2List = arr;
      },

      delCheckedEvt2(userId, type) {
        if (type === "T") {
          const result = this.getParentIds(this.teacherList, userId)
          console.log("mmmm", result)
          this.selectedTeacher2List = this.selectedTeacher2List.filter(
            (v) => v.userId !== userId
          );
          this.checkedTeacher2List = this.checkedTeacher2List.filter(
            (v) => v !== userId && !result.includes(v)
          );
        } else if (type === "S") {
          const result = this.getParentIds(this.studentList, userId)
          console.log("mmmm", result)
          this.selectedStudentList = this.selectedStudentList.filter(
            (v) => v.userId !== userId
          );
          this.checkedStudentList = this.checkedStudentList.filter(
            (v) => v !== userId && !result.includes(v)
          );

        } else {
          this.selectedRoleList = this.selectedRoleList.filter(
            (v) => v.roleCode !== userId
          );
          this.checkedRoleList = this.checkedRoleList.filter((v) => v !== userId);
        }
      },
    }
  }
</script>
<style scoped="scoped" lang="scss">
  .red {
    color: red;
  }

  .yellow {
    color: #FF8948;
  }

  .body {
    padding: 24px 0;
  }

  ::v-deep .ant-tabs-nav-container {
    margin-left: 24px;
  }

  .day-statistics {
    margin: 0 24px;

    .day-form {
      display: flex;
      flex-wrap: wrap;

      .day-form-tit {
        white-space: nowrap;
      }

      .form-item {
        display: flex;
        align-items: center;
        margin: 0 0 24px 0;
        width: 260px;
        margin-right: 20px;
      }

      .day-form-in {
        width: 220px;
      }

      .day-form-btn {
        margin-right: 10px;
      }
    }
  }



  .checked-area {
    margin: 12px 0;

    .item {
      display: inline-flex;
      align-items: center;
      height: 32px;
      text-align: center;
      line-height: 32px;
      background: #f2f4f5;
      margin: 6px 12px;
      margin-left: 0;
      border-radius: 4px;
      padding: 0 12px;
      user-select: none;
      color: #999;

      &:hover {
        color: #666;
        background: #e5e5e5;
      }

      .label {
        display: inline-block;
        max-width: 120px;
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
        color: #333;
        font-size: 14px;
        font-weight: 400;
        margin-right: 8px;
      }

      .icon {
        cursor: pointer;
      }
    }
  }
</style>
